<?php

namespace app\command;

use app\model\DistributionSetting;
use app\model\Feed;
use app\model\Live;
use app\model\LiveGoods;
use app\model\Talent;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use util\Logger;
use Wechat\CommerceApp;

class LiveGoodsTaskCommand extends Command
{
    protected function configure()
    {
        $this->setName('live-goods')
            ->setDescription('获取达人平台推广的短视频信息');
    }

    protected function execute(Input $input, Output $output)
    {
        Log::init([
            'type'        => 'file',
            'apart_level' => ['error'],
            'level'       => ['error'],
            'path'        => app()->getRootPath() . "runtime/log/live-goods/",
            'max_files'   => 5,
        ]);
        $live = Live::column('appid');
        foreach ($live as $talent_appid) {
            $next_key = '';
            try {
                do {
                    [$goods_list, $next_key, $has_more] = CommerceApp::getInstance()->getLiveGoodsList($talent_appid, $next_key);
                    $next_key = $next_key ?? '';
                    $has_more = $has_more ?? false;

                    if ($goods_list) {
                        $ids = $save = [];
                        foreach ($goods_list as $item) {
                            $ids[] = $item['product_id'];
                        }
                        $lists = LiveGoods::where('appid', $talent_appid)->where('product_id', 'in', $ids)->column('product_id, id');

                        foreach ($goods_list as $item) {
                            if (!isset($lists[$item['product_id']])) {
                                $save[] = [
                                    'appid'           => $talent_appid,
                                    'product_id'      => $item['product_id'],
                                    'product_name'    => $item['product_name'],
                                    'product_img_url' => $item['product_img_url'],
                                    'product_price'   => $item['product_price'],
                                    'commission'      => $item['predict_commission_amount'],
                                ];
                            }
                        }
                        if ($save) {
                            (new LiveGoods())->saveAll($save);
                        }
                    }
                } while ($has_more);
            } catch (\Exception $e) {
                $log = [
                    'msg'   => '获取直播商品列表失败',
                    'error' => $e->getMessage(),
                    'file'  => $e->getFile(),
                    'line'  => $e->getLine(),
                ];
                Log::error($log);
                continue;
            }
        }
    }
}
